package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.bean.salesChicken.Driver;
import com.example.demo.bean.salesChicken.HouseInformation;
import com.example.demo.bean.salesChicken.SalesCarInformation;
import com.example.demo.bean.salesChicken.SalesChickenDetail;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.net.URIBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 商品鸡外卖相关控制器，处理车辆、司机、销售等业务逻辑
@Controller
public class ChickenSell {

    // HTTP客户端，用于发送HTTP请求
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 登录后获取的token，用于后续接口调用
    String token = "";

    /**
     * 登录页面入口
     * @return 登录页面视图
     */
    @RequestMapping("/chickenSell")
    public String login() {
        // 返回登录页面视图
        return "chickensell/login";
    }

    /**
     * 获取车辆信息，并将司机列表传递到前端页面
     * @param userCode 用户代码
     * @param password 密码
     * @param model Spring MVC模型
     * @return 车辆列表页面
     */
    @RequestMapping("/getCar")
    public String getCar(@RequestParam("userCode") String userCode,
                         @RequestParam("password") String password, Model model)
            throws IOException, ParseException, URISyntaxException {
        // 校验用户输入
        if (userCode == null || password == null) {
            throw new IllegalArgumentException("用户代码和密码不能为空");
        }
        // 创建HTTP客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 登录获取token
        HttpPost httpPost = new HttpPost("http://oa.shuanghui.net:9081/login");
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        // 组装登录请求体
        String json = "{\"pwd\":\"" + password + "\",\"userCode\":\"" + userCode + "\"}";
        StringEntity formEntity = new StringEntity(json, ContentType.APPLICATION_JSON.withCharset("UTF-8"));
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = null;
        try {
            // 执行登录请求
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 登录成功，获取token
        if (response.getCode() == 200) {
            String content = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject jsonObject = new JSONObject(content);
            token = jsonObject.getString("token");
        }
        // 查询车辆登记信息
        URIBuilder uriBuilder = new URIBuilder("http://oa.shuanghui.net:9081/breed/mobile/chickenMobile/vehicleRegister/queryLastPlatoonCar");
        uriBuilder.setParameter("isComplete", "N");
        uriBuilder.setParameter("pageNum", "1");
        uriBuilder.setParameter("pageSize", "10");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.setHeader("Token", token);
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        CloseableHttpResponse response2 = httpClient.execute(httpGet);
        String o = "";
        List driverList = new ArrayList();
        if (response2.getCode() == 200) {
            // 解析车辆信息，组装司机列表
            HttpEntity httpEntity = response2.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf-8");
            JSONObject contentObject = new JSONObject(content);
            JSONArray dataArray = (JSONArray) contentObject.get("data");
            for (int i = 0; i < dataArray.length(); i++) {
                Driver driver = new Driver();
                o = dataArray.get(i).toString();
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(o);
                driver.setDriverName(jsonObject.getString("driver"));
                driver.setTelePhone(jsonObject.getString("telephone"));
                driver.setLicenseNum(jsonObject.getString("licenseNum"));
                driver.setSourSeqNo(jsonObject.getString("sourSeqNo"));
                driverList.add(driver);
            }
        }
        // 将司机列表传递到前端页面
        model.addAttribute("driverList", driverList);
        return "chickensell/carList";
    }

    /**
     * 发送车辆签到申请到后端
     * @param driver 司机姓名
     * @param licenseNum 车牌号
     * @param telephone 电话
     * @param sourSeqNo 源序号
     * @return 后端返回内容
     */
    @PostMapping("/breed/mobile/product/proSellVehicle/addSellVehicle")
    @ResponseBody
    public String addSellVehicle(@RequestParam String driver, @RequestParam String licenseNum,
                                 @RequestParam String telephone, @RequestParam String sourSeqNo) throws URISyntaxException, IOException, ParseException {
        // 控制台打印参数，便于调试
        System.out.println(driver + " " + licenseNum + " " + telephone);
        // 构建签到请求
        HttpPost httpPost = new HttpPost("http://oa.shuanghui.net:9081/breed/mobile/product/proSellVehicle/addSellVehicle");
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        // 组装请求体
        String json = "{\"driver\":\"" + driver + "\",\"licenseNum\":\"" + licenseNum + "\",\"telephone\":\"" + telephone + "\",\"sourSeqNo\":\"" + sourSeqNo + "\"}";
        StringEntity formEntity = new StringEntity(json, ContentType.APPLICATION_JSON.withCharset("UTF-8"));
        httpPost.setEntity(formEntity);
        httpPost.setHeader("Token", token);
        // 发送请求
        CloseableHttpResponse response2 = httpClient.execute(httpPost);
        String content = "";
        if (response2.getCode() == 200) {
            // 解析返回内容
            HttpEntity httpEntity = response2.getEntity();
            content = EntityUtils.toString(httpEntity, "utf-8");
            JSONObject contentObject = new JSONObject(content);
            Object data = contentObject.get("data");
        }
        return content;
    }

    /**
     * 获取销售车辆头部信息列表，并将部分信息存入session
     * @param session HttpSession
     * @return 销售车辆信息列表
     */
    @RequestMapping("/breed/mobile/product/sell/headList")
    @ResponseBody
    public List headList(HttpSession session) throws URISyntaxException, IOException, ParseException {
        // 查询销售车辆头部信息
        URIBuilder uriBuilder = new URIBuilder("http://oa.shuanghui.net:9081/breed/mobile/product/sell/headList");
        uriBuilder.setParameter("isComplete", "N");
        uriBuilder.setParameter("pageNum", "1");
        uriBuilder.setParameter("pageSize", "10");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.setHeader("Token", token);
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        CloseableHttpResponse response2 = httpClient.execute(httpGet);
        String o = "";
        List<SalesCarInformation> SalesCarInformationList = new ArrayList();
        if (response2.getCode() == 200) {
            // 解析返回的车辆头部信息
            HttpEntity httpEntity = response2.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf-8");
            System.out.println("Response content: " + content);
            JSONObject contentObject = new JSONObject(content);
            JSONArray dataArray = (JSONArray) contentObject.get("data");
            for (int i = 0; i < dataArray.length(); i++) {
                SalesCarInformation salesCarInformation = new SalesCarInformation();
                o = dataArray.get(i).toString();
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(o);
                // 解析明细列表
                com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("detailList");
                List<SalesChickenDetail> detailList = new ArrayList<>();
                if (jsonArray != null) {
                    for (int j = 0; j < jsonArray.size(); j++) {
                        com.alibaba.fastjson.JSONObject jsonObject1 = jsonArray.getJSONObject(j);
                        SalesChickenDetail detail = jsonObject1.toJavaObject(SalesChickenDetail.class);
                        detailList.add(detail);
                    }
                    salesCarInformation.setDetailList(detailList);
                }
                // 设置车辆头部信息
                salesCarInformation.setDriverName(jsonObject.getString("driver"));
                salesCarInformation.setTelePhone(jsonObject.getString("telephone"));
                salesCarInformation.setLicenseNum(jsonObject.getString("licenseNum"));
                salesCarInformation.setCreateDateTime(jsonObject.getString("createDateTime"));
                salesCarInformation.setCustomerName(jsonObject.getString("customerName"));
                salesCarInformation.setSourSeqNo(jsonObject.getString("sourSeqNo"));
                salesCarInformation.setSeqNo(Integer.valueOf(jsonObject.getString("seqNo")));
                salesCarInformation.setSurplusFrameNum(Integer.valueOf(jsonObject.getString("surplusFrameNum")));
                salesCarInformation.setStandardNum(Integer.valueOf(jsonObject.getString("standardNum")));
                salesCarInformation.setCustomerId(Integer.valueOf(jsonObject.getString("customerId")));
                SalesCarInformationList.add(salesCarInformation);
            }
        }
        // 将部分信息存入session，便于后续操作
        session.setAttribute("headSeqNo", SalesCarInformationList.get(0).getSeqNo());
        System.out.println("headSeqNo" + SalesCarInformationList.get(0).getSeqNo());
        session.setAttribute("customerId", SalesCarInformationList.get(0).getCustomerId());
        System.out.println("customerId" + SalesCarInformationList.get(0).getCustomerId());
        return SalesCarInformationList;
    }

    /**
     * 获取生产鸡舍信息列表
     * @return 鸡舍信息列表
     */
    @GetMapping("/breed/mobile/chicken/common/getProDuctHouse")
    @ResponseBody
    public List getProDuctHouse() throws URISyntaxException, IOException, ParseException {
        // 查询鸡舍信息
        URIBuilder uriBuilder = new URIBuilder("http://oa.shuanghui.net:9081/breed/mobile/chicken/common/getProDuctHouse");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.setHeader("Token", token);
        CloseableHttpResponse response2 = httpClient.execute(httpGet);
        String o = "";
        List houseInformationList = new ArrayList();
        if (response2.getCode() == 200) {
            // 解析鸡舍信息
            HttpEntity httpEntity = response2.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf-8");
            JSONObject contentObject = new JSONObject(content);
            JSONArray dataArray = (JSONArray) contentObject.get("data");
            for (int i = 0; i < dataArray.length(); i++) {
                HouseInformation houseInformation = new HouseInformation();
                o = dataArray.get(i).toString();
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(o);
                houseInformation.setOrgId(Integer.valueOf(jsonObject.getString("orgId")));
                houseInformation.setHouseId(Integer.valueOf(jsonObject.getString("houseId")));
                houseInformation.setHouseCode(jsonObject.getString("houseCode"));
                houseInformation.setHouseName(jsonObject.getString("houseName"));
                houseInformation.setInvQty(Integer.valueOf(jsonObject.getString("invQty")));
                houseInformation.setBatch(jsonObject.getString("batch"));
                houseInformation.setDay(Integer.valueOf(jsonObject.getString("day")));
                houseInformation.setItemCode(Integer.valueOf(jsonObject.getString("itemCode")));
                houseInformation.setItemName(jsonObject.getString("itemName"));
                houseInformation.setStockSeqNo(Integer.valueOf(jsonObject.getString("stockSeqNo")));
                houseInformationList.add(houseInformation);
            }
        }
        return houseInformationList;
    }

    /**
     * 新增销售记录
     * @param session HttpSession
     * @param data 前端传递的销售数据
     * @return 后端返回内容
     */
    @PostMapping("/breed/mobile/product/sell/add")
    @ResponseBody
    public String sellAdd(HttpSession session, @RequestBody Map<String, Object> data) throws IOException, ParseException {
        // 构建销售新增请求
        HttpPost httpPost = new HttpPost("http://oa.shuanghui.net:9081/breed/mobile/product/sell/add");
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        // 从session获取头部信息
        Integer headSeqNo = (Integer) session.getAttribute("headSeqNo");
        Integer customerId = (Integer) session.getAttribute("customerId");
        Integer counterpoise = 0; // 默认地磅重量为0
        Integer price = 0; // 默认价格为0
        Map houseInfo = (Map) data.get("houseInfo");
        // 组装请求参数
        String json = "{\"batch\":\"" + houseInfo.get("batch") + "\",\"customerId\":\"" + customerId +
                "\",\"headSeqNo\":\"" + headSeqNo + "\",\"houseId\":\"" + houseInfo.get("houseId") +
                "\",\"boxNum\":\"" + data.get("boxNum") + "\",\"standardNum\":\"" + data.get("standardNum") +
                "\",\"sumNum\":\"" + data.get("sumNum") + "\",\"fraction\":\"" + data.get("fraction") +
                "\",\"counterpoise\":\"" + counterpoise + "\",\"price\":\"" + price +
                "\"}";
        System.out.println(json);
        StringEntity formEntity = new StringEntity(json, ContentType.APPLICATION_JSON.withCharset("UTF-8"));
        httpPost.setEntity(formEntity);
        httpPost.setHeader("Token", token);
        // 发送请求
        CloseableHttpResponse response2 = httpClient.execute(httpPost);
        String content = "";
        JSONObject contentObject = null;
        if (response2.getCode() == 200) {
            // 解析返回内容
            HttpEntity httpEntity = response2.getEntity();
            content = EntityUtils.toString(httpEntity, "utf-8");
            contentObject = new JSONObject(content);
            System.out.println(contentObject);
        }
        return content;
    }
}

    
